package com.cloud.xtools.common.validator;

import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.cloud.xtools.common.mapper.DynamicSqlMapper;
import com.cloud.xtools.common.validator.annotation.EntityExist;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Daixinguo
 */
public class EntityExistValidator implements ConstraintValidator<EntityExist,Object> {

    /**
     * 数据库表名
     */
    private String tableName;
    /**
     * 需要验证的字段名
     */
    private String fieldName;

    /**
     * 动态SQL查询器
     */
    @Autowired
    private DynamicSqlMapper dynamicSqlMapper;

    @Override
    public void initialize(EntityExist constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.tableName = SqlHelper.table(constraintAnnotation.entity()).getTableName();
        this.fieldName = constraintAnnotation.field();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null || value.toString().isEmpty()) {
            return true;
        }
        // 创建参数映射，将待验证的字段值放入参数映射中
        Map<String, Object> params = new HashMap<>();
        params.put(fieldName, value);
        String sql = String.format("SELECT COUNT(*) FROM %s WHERE %s = #{params[%s]}", tableName, fieldName, fieldName);

        // 执行SQL查询，获取数据库中匹配记录的数量
        Long count = (Long) dynamicSqlMapper.selectBySql(sql, params);

        return count == 1;
    }
}
